package com.bestcem.xm.cjm.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bestcem.xm.cjm.controller.vo.ClientJourneyDataVo;
import com.bestcem.xm.cjm.controller.vo.ClientJourneyVo;
import com.bestcem.xm.cjm.entity.*;
import com.bestcem.xm.cjm.service.*;
import com.bestcem.xm.cjm.util.PageUtil;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/cjm/")
public class CjmSettingsController {

    private @NonNull CjmPackageService cjmPackageService;
    private @NonNull CjmClientjourneyService cjmClientjourneyService;
    private @NonNull CjmColumnsService cjmColumnsService;
    private @NonNull CjmRowsService cjmRowsService;
    private @NonNull CjmUserclientjourneyService cjmUserclientjourneyService;

    @ApiOperation(value = "复制客户旅程")
    @PostMapping("/clientjourney_copy/{id:[a-f0-9]{24}}")
    public XmResultJson<?> copyJourney(@PathVariable(value = "id") String id, @RequestBody JSONObject param) {
        param.put("orgID", SecurityContextHolder.getOrgId());
        param.put("user_id", SecurityContextHolder.getUserId());
        return XmResultJson.success(cjmClientjourneyService.copyJourney(id, param));
    }

    @ApiOperation(value = "更新文件夹")
    @PutMapping("/packages/{id:[a-f0-9]{24}}")
    public XmResultJson<?> updatePackage(@PathVariable(value = "id") String id, @RequestBody JSONObject param) {
        JSONObject query_params = getFilterFromJwt();
        query_params.put("id", id);

        CjmPackage query = query_params.toJavaObject(CjmPackage.class);
        LambdaQueryWrapper<CjmPackage> queryWrapper = new LambdaQueryWrapper<>(query);
        CjmPackage p = cjmPackageService.getOne(queryWrapper);
        if (Objects.isNull(p)) {
            return XmResultJson.fail(-1, String.format("Package[id=%s] not found", id));
        }

        //p = param.toJavaObject(CjmPackage.class);
        //p.setId(id);
        //cjmPackageService.updateById(p);
        //
        //JSONObject ret = new JSONObject();
        //ret.put("id", id);
        //return XmResultJson.success(ret);
        return cjmPackageService.updatePackage(id, param);
    }

    @ApiOperation(value = "删除文件夹")
    @DeleteMapping("/packages/{id:[a-f0-9]{24}}")
    public XmResultJson<?> deletePackage(@PathVariable(value = "id", required = false) String id, @RequestBody JSONObject param) {
        JSONObject query_params = getFilterFromJwt();

        if (StrUtil.isNotBlank(id)) {
            query_params.put("id", id);

            CjmPackage query = query_params.toJavaObject(CjmPackage.class);
            LambdaQueryWrapper<CjmPackage> queryWrapper = new LambdaQueryWrapper<>(query);
            CjmPackage p = cjmPackageService.getOne(queryWrapper);
            if (Objects.isNull(p)) {
                return XmResultJson.fail(-1, String.format("Package[id=%s] not found", id));
            }

            /*boolean flag = cjmPackageService.removeById(id);
            JSONObject ret = new JSONObject();
            ret.put("deletedCount", flag ? 1 : 0);
            return XmResultJson.success(ret);*/
            return cjmPackageService.deletePackageById(id);
        } else {
            if (!param.containsKey("idList")) {
                return XmResultJson.fail(-1, ":idList is required");
            }
            if (!(param.get("idList") instanceof List)) {
                return XmResultJson.fail(-1, ":idList must be list");
            }

            /*CjmPackage query = query_params.toJavaObject(CjmPackage.class);
            LambdaQueryWrapper<CjmPackage> wrapper = new LambdaQueryWrapper<>(query);
            wrapper.in(CjmPackage::getId, param.getJSONArray("idList"));
            boolean flag = cjmPackageService.remove(wrapper);
            JSONObject ret = new JSONObject();
            ret.put("deletedCount", flag ? param.getJSONArray("idList").size() : 0);
            return XmResultJson.success(ret);*/
            return cjmPackageService.deletePackages(query_params, param);
        }
    }

    @ApiOperation(value = "查询")
    @GetMapping("/packages/")
    public XmResultJson<?> getPackageList(HttpServletRequest request) {
        //todo python 这个接口还有do_page,页面上暂时没找到，只写了查do_list
        if (PageUtil.isPageQuery(request)) {
            //do_page;
        }
        JSONObject query_params = getFilterFromJwt();
        query_params.putAll(ServletUtil.getParamMap(request));
        CjmPackage query = query_params.toJavaObject(CjmPackage.class);
        // 非eq的需要单独处理，这里页面上暂时没发现
        LambdaQueryWrapper<CjmPackage> wrapper = new LambdaQueryWrapper<>(query);
        List<CjmPackage> list = cjmPackageService.list(wrapper);
        return XmResultJson.success(list);
    }

    @GetMapping("/packages/{id:[a-f0-9]{24}}")
    public XmResultJson<?> getPackageById(@PathVariable(value = "id") String id) {
        CjmPackage p = cjmPackageService.getById(id);
        if (p == null) {
            return XmResultJson.fail(-1, String.format("Package[id={%s}] not found", id));
        }
        return XmResultJson.success(p);
    }

    @PostMapping("/packages/")
    public XmResultJson<?> addPackage(@RequestBody JSONObject param) {
        JSONObject query_params = getFilterFromJwt();
        query_params.putAll(param);
        return cjmPackageService.addPackage(query_params);
    }

    @GetMapping("/publish/clientjourneys/")
    public XmResultJson<?> getClientJourney() {
        JSONObject params = getFilterFromJwt();
        CjmClientjourney query = params.toJavaObject(CjmClientjourney.class);
        LambdaQueryWrapper<CjmClientjourney> wrapper = new LambdaQueryWrapper<>(query);
        wrapper.isNotNull(CjmClientjourney::getParentId);
        wrapper.ne(CjmClientjourney::getParentId, "''");
        wrapper.ne(CjmClientjourney::getParentId, "'null'");
        wrapper.ne(CjmClientjourney::getParentId, "'NULL'");
        List<CjmClientjourney> list = cjmClientjourneyService.list(wrapper);
        List<ClientJourneyVo> voList = cjmClientjourneyService.getPublishClientJourney(list, SecurityContextHolder.getUserId());
        JSONObject ret = new JSONObject();
        ret.put("data", voList);
        return XmResultJson.success(ret);
    }

    @ApiOperation(value = "批量删除旅程")
    @DeleteMapping("/clientjourneys/")
    public XmResultJson<?> deleteClientJourneys(@RequestBody JSONObject param) {
        if (!param.containsKey("idList")) {
            return XmResultJson.fail(-1, ":idList is required");
        }
        if (!(param.get("idList") instanceof List)) {
            return XmResultJson.fail(-1, ":idList must be list");
        }
        JSONObject query_params = getFilterFromJwt();
        Integer superRole = SecurityContextHolder.getToken().getSuperRole();
        String userId = SecurityContextHolder.getUserId();
        return XmResultJson.success(cjmClientjourneyService.deleteClientJourneys(query_params, param, superRole, userId));
    }

    @ApiOperation(value = "更新列")
    @PutMapping("/columnss/{id:[a-f0-9]{24}}")
    public XmResultJson<?> updateColumns(@PathVariable(value = "id") String id, @RequestBody JSONObject param) {
        JSONObject query_params = getFilterFromJwt();
        query_params.remove("user_id");
        query_params.put("id", id);

        CjmColumns query = query_params.toJavaObject(CjmColumns.class);
        LambdaQueryWrapper<CjmColumns> queryWrapper = new LambdaQueryWrapper<>(query);
        CjmColumns columns = cjmColumnsService.getOne(queryWrapper);
        if (Objects.isNull(columns)) {
            return XmResultJson.fail(-1, String.format("Columns[id=%s] not found", id));
        }

        return cjmColumnsService.updateColumns(id, param);
    }

    @ApiOperation(value = "关联仪表盘")
    @PutMapping("/clientjourney_dashboard/{id:[a-f0-9]{24}}")
    public XmResultJson<?> bindDashboard(@PathVariable(value = "id") String id, @RequestBody JSONObject param) {
        CjmClientjourney clientjourney = cjmClientjourneyService.getById(id);
        if (Objects.isNull(clientjourney)) {
            return XmResultJson.fail(-1, String.format("clientjourney[id=%s] not found", id));
        }
        Integer superRole = SecurityContextHolder.getToken().getSuperRole();
        String userId = SecurityContextHolder.getUserId();
        if ((superRole == null || superRole == 0) && !userId.equals(clientjourney.getUserId())) {
            return XmResultJson.fail(-1, "PermissionDeny");
        }
        JSONObject dashboard_data = param.getJSONObject("dashboard_data");
        if (ObjectUtils.isEmpty(dashboard_data)) {
            JSONObject ret = new JSONObject();
            ret.put("id", id);
            return XmResultJson.success(ret);
        }
        return cjmClientjourneyService.bindDashboard(clientjourney, dashboard_data);
    }

    @ApiOperation(value = "获取客旅程发布版本数据")
    @GetMapping("/clientjourneys/{id:[a-f0-9]{24}}")
    public XmResultJson<?> getClientJourneyData(@PathVariable(value = "id") String id) {
        CjmClientjourney clientjourney = cjmClientjourneyService.getById(id);
        if (Objects.isNull(clientjourney)) {
            return XmResultJson.fail(-1, String.format("clientjourney[id=%s] not found", id));
        }
        ClientJourneyDataVo ret = new ClientJourneyDataVo();
        BeanUtil.copyProperties(clientjourney, ret);
        //拓展字段
        List<CjmRows> rows = new ArrayList<>();
        List<CjmColumns> columns = new ArrayList<>();
        JSONArray.parseArray(clientjourney.getRows())
                .forEach(a -> rows.add(cjmRowsService.getById(a.toString())));
        JSONArray.parseArray(clientjourney.getColumns())
                .forEach(a -> columns.add(cjmColumnsService.getById(a.toString())));
        ret.setColumnsData(columns);
        ret.setRowsData(rows);

        CjmUserclientjourney user_cjm = cjmUserclientjourneyService.getOne(
                Wrappers.<CjmUserclientjourney>lambdaQuery()
                        .eq(CjmUserclientjourney::getClientjourneyId, id)
        );
        ret.setUserclientjourney(user_cjm);

        return XmResultJson.success(ret);
    }

    @NotNull
    private static JSONObject getFilterFromJwt() {
        JSONObject query_params = new JSONObject();
        query_params.put("orgID", SecurityContextHolder.getOrgId());
        query_params.put("user_id", SecurityContextHolder.getUserId());
        return query_params;
    }
}